<template>
  <el-dialog :visible.sync="dialogVisible" :before-close="cancel">
    <template slot="title">
      <div>{{vipType==0?'批量修改VIP等级':'批量解锁VIP等级'}}</div>
    </template>
    <el-form  :model="form" ref="refForm">
      <el-form-item label="勾选用户名：" style="display:flex;">
        <div>{{names.length>30?names.slice(0,30).join('、')+'等'+names.length+'个账户':names.join('、')}}</div>
      </el-form-item>
      <el-form-item label="输入用户名：" style="display:flex;">
        <el-input type="textarea" rows="4" v-model="form.username" @change="usersChange"></el-input>
        <el-tip>注：多个用户名请用","隔开</el-tip>
        <el-col :span="24" v-if="inValidateUsers.length>0">
        以下账号不存在：
        <span style="color: red;text-decoration: underline;padding: 5px;"
              v-for="user in inValidateUsers">{{user}}</span>
      </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="clickNext" :loading="loading">下一步</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { form, grid } from '@/build';
import { messageType } from '@/const/enum';
import ElTip from '@/components/Tip/index';

import {
  vipNameSearch,
  vipBtachUnlock,

} from '@/services/api/member';
import { validateAdjustmentUsers } from '@/services/api/adjustment';

export default {

  name: 'vip-level-dialog',
  components: { ElTip },
  props: ['dialogVisible', 'vipType', 'rows'],

  mixins: [form, grid],

  data() {
    return {
      isClick: false,
      usernames: [],
      rowsData: this.rows,
      form: {
        username: '',
      },
      info: {},
      inValidateUsers: [], // 存放不存在的用户
    };
  },
  computed: {
    names() {
      const name = [];
      _.each(this.rows, (item) => {
        name.push(item.username);
      });
      return name;
    },
  },

  methods: {
    usersChange(val) {
      val = val.replace(/，/g, ',');
      const users = _.uniq(val.split(',')).filter(d => d).join(',');
      this.$_validateUsers(users);
    },
    $_validateUsers(users) { // 查询用户是否存在
      validateAdjustmentUsers({ users }).then(([result, data]) => {
        if (result) {
          this.inValidateUsers = data;
          if (data.length == 0 && this.isClick) {
            this.doNext();
          }
        }
      });
    },
    cancel() {
      this.$emit('cancel');
    },
    clickNext() {
      this.isClick = true;
      if (this.form.username == '') {
        this.doNext();
      }
    },
    doNext() { // vipType:0,修改等级 1，解锁等级
      if (this.vipType == 0) {
        if (this.form.username) { // 请求接口,查詢用戶信息
          this.doGet({ action: 'getinfo' });
        } else { // 直接跳轉
          this.rowsData = _.filter(this.rowsData, item => item.lockStatus == 0);// 去掉vip状态已锁定的数据
          this.$emit('getTableType', { tableType: 0, rows: this.rowsData });
          setTimeout(() => {
            this.cancel();
          }, 500);
        }

      } else { // 解锁等级
        this.usernames = [];
        _.each(this.rowsData, (item) => {
          this.usernames.push(item.username);
        });
        if (this.form.username) {
          this.usernames = this.usernames.concat(this.form.username.split(','));// 拼接上一次的
        }
        // console.log(JSON.stringify(this.usernames));
        this.unLockLevel(this.usernames);
      }
    },
    async unLockLevel(data) { // 批量解锁
      try {
        await this.$confirm('是否需要批量解锁选中的账户VIP等级？解锁后的账户会受VIP升降级规则限制', '批量解锁VIP等级', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const [status, result] = await vipBtachUnlock({
          usernames: this.usernames.join(','),
        });
        if (!status) throw new Error(result.message);
        this.$message({
          type: 'success',
          message: '解锁成功!',
        });
        this.$parent.getAll();
        this.cancel();
      } catch (e) {
        if (e === messageType.cancel) return;
        this.$message({
          type: 'error',
          message: `解锁失败!${e.message || ''}`,
        });
        this.cancel();
      }
    },
  },
  mounted() {
    this.bindGet(vipNameSearch, 'info', {// 根据用户名查询用户vip信息
      action: 'getinfo',
      sendingData: { usernames: this.form.username },
      beforeSend: data => ({
        usernames: this.form.username,
      }),
      callback: ([result, data]) => {
        if (!result) return;
        this.rowsData = this.rowsData.concat(data);
        this.rowsData = _.filter(this.rowsData, item => item.lockStatus == 0);// 去掉vip状态已锁定的数据
        this.$emit('getTableType', { tableType: 0, rows: this.rowsData });
        setTimeout(() => {
          this.cancel();
        }, 500);
      },

    });

  },
};
</script>

<style scoped lang="scss">
/deep/ .el-form-item__content{width:85%}
</style>
